﻿using DevExpress.XtraEditors;
using EkStudio.com.common.dbconn;
using EkStudio.com.common.unit;
using EkStudio.com.ui.unitbill.property.Event;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace EkStudio.com.ui.form
{
    public partial class ModuleAttachForm :XtraForm
    {

        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(ModuleAttachForm));

        private ProjectRootPanel rootPanel = null;

        private DataTable data = null;

        private delegate void UpdateStatusDelegate(string key, string xml);

        public ModuleAttachForm()
        {
            InitializeComponent();
            InitForm();
        }


        private void InitForm()
        {
            data = new DataTable("TableName");
            data.Columns.Add("CheckStatus", typeof(bool));
            data.Columns.Add("FileName", typeof(string));
            data.Columns.Add("UploadDate", typeof(string));
            data.Columns.Add("FileSize", typeof(string));
            GridAttchControl.DataSource = data;
        }


        public ProjectRootPanel RootPanel
        {
            get
            {
                return rootPanel;
            }

            set
            {
                rootPanel = value;
                loadAttach();
            }
        }
        /// <summary>
        /// 加载附件
        /// </summary>
        private void loadAttach()
        {
            data.Rows.Clear();
            if (rootPanel != null)
            {
                Dictionary<string, string> param = new Dictionary<string, string>();
                //param.Add("loadAttach", "true");
                param.Add("loadType", "0");
                rootPanel.Http.AsyncPost(ProjectUtil.HTTP_ATTACH_LIST_URL, param, "", CallBackFunction);
            }


            GridAttchView.RefreshData();
        }
        /// <summary>
        /// 异步回調函数，当前方法会在异步线程执行 要转成同步
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CallBackFunction(object sender, PropertyDataEvent e)
        {
            //异步转同步
            this.BeginInvoke(new UpdateStatusDelegate(TbCallEvent), new object[] { e.Key, (string)e.Value });
        }

        private void TbCallEvent(string key, string xml)
        {
            if (key== "OK")
            {
                XmlDocument doc = new XmlDocument();
                try
                {
                    doc.LoadXml(xml);
                    XmlElement root = doc.DocumentElement;
                    XmlNodeList list = root.SelectNodes("item");
                    if (list != null && list.Count > 0)
                    {
                        foreach(XmlNode node in list)
                        {
                            string name = node.Attributes["fileName"].Value;
                            string date = node.Attributes["fileDate"].Value;
                            string size = node.Attributes["fileSize"].Value;
                            DataRow row = data.NewRow();

                            //data.Columns.Add("CheckStatus", typeof(bool));
                            //data.Columns.Add("FileName", typeof(string));
                            //data.Columns.Add("UploadDate", typeof(string));
                            //data.Columns.Add("FileSize", typeof(int));
                            row["CheckStatus"] = false;
                            row["FileName"] = name;
                            row["UploadDate"] = date;
                            row["FileSize"] = size;
                            data.Rows.Add(row);
                        }
                    }
                }
                finally
                {
                    GridAttchView.RefreshData();
                }


            }else
            {
                RootPanel.ShowAlert("附件","加载附件失败");
            }
        }

        /// <summary>
        /// 重新加载列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnRefault_Click(object sender, System.EventArgs e)
        {
            loadAttach();
        }
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnUpload_Click(object sender, System.EventArgs e)
        {
            if(openFile.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFile.FileName;
                string fileName = openFile.SafeFileName;
                bool success = false;
                try
                {
                    success = RootPanel.Http.FileUpLoadResources(ProjectUtil.HTTP_FILEUPLOAD_URL, fileName, filePath, HttpConnectUnit.TYPE_CONFIG_ATTACH_FILE);
                }catch(Exception ee)
                {
                    logger.Info("", ee);
                }
                if (success) loadAttach();
                
            }
        }
        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDownload_Click(object sender, System.EventArgs e)
        {
            if (data.Rows.Count > 0)
            {
                DataRow check = null;
                foreach(DataRow row in data.Rows)
                {
                    if((bool)row["CheckStatus"])
                    {
                        check = row;
                        break;
                    }
                }
                if (check != null)
                {
                    string attachName = (string)check["FileName"];
                    saveFile.FileName = attachName;
                    if(saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        string filePath = saveFile.FileName;
                        bool success = true;
                        if (File.Exists(filePath)){
                            try
                            {
                                File.Delete(filePath);
                            }catch(Exception ee)
                            {
                                logger.Error("删除文件失败", ee);
                                RootPanel.ShowAlert("提示", "选择的文件存在且被占用,保存失败");
                                success = false;
                            }
                        }
                        try
                        {
                            if (success)
                            {
                                RootPanel.Http.FileLoadResources(ProjectUtil.HTTP_FILELOAD_URL, attachName, filePath, HttpConnectUnit.TYPE_CONFIG_ATTACH_FILE);
                                RootPanel.ShowAlert("提示", "下载成功");
                            }
                        } catch(Exception ee)
                        {
                            logger.Error("删除帐套附件失败", ee);
                        }
                        
                    }
                }
                else
                {
                    RootPanel.ShowAlert("提示", "请选择要下载的附件");
                }
            }
        }
        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDelete_Click(object sender, System.EventArgs e)
        {
            if (data.Rows.Count > 0)
            {
                DataRow check = null;
                foreach (DataRow row in data.Rows)
                {
                    if ((bool)row["CheckStatus"])
                    {
                        check = row;
                        break;
                    }
                }
                if (check != null)
                {
                    string attachName = (string)check["FileName"];
                    if(XtraMessageBox.Show(string.Format("您确认删除要附件[{0}]吗？",attachName),"提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question) == DialogResult.OK)
                    {
                        Dictionary<string, string> param = new Dictionary<string, string>();
                        param.Add("fileType", Convert.ToString(HttpConnectUnit.TYPE_CONFIG_ATTACH_FILE));
                        param.Add("fileName", attachName);
                        try
                        {
                            string xml = RootPanel.Http.PostHttp(ProjectUtil.HTTP_ATTACH_DELETE_URL, param, "");
                            XmlDocument doc = new XmlDocument();
                            doc.LoadXml(xml);
                            XmlElement root = doc.DocumentElement;
                            if (root.SelectSingleNode("result") != null)
                            {
                                XmlNode node = root.SelectSingleNode("result");
                                if(node.InnerText == "0")
                                {
                                    this.loadAttach();
                                    RootPanel.ShowAlert("提示", "删除成功");
                                }
                                else
                                {
                                    RootPanel.ShowAlert("提示", "删除失败");
                                }
                            }
                        }
                        catch (Exception ee)
                        {
                            logger.Error("删除文件执行异常", ee);
                        }
                    }
                }
                else
                {
                    RootPanel.ShowAlert("提示", "请选择要删除的附件");
                }
            }
        }

        private void GridAttchView_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "CheckStatus")
            {
                if (data.Rows.Count > 0)
                {
                    for (int i = 0; i < data.Rows.Count; i++)
                    {
                        if (i != e.RowHandle)
                        {
                            data.Rows[i]["CheckStatus"] = false;
                        }
                    }
                    GridAttchView.RefreshData();
                }
            }
        }
    }
}